import { Workbook } from 'exceljs';

export const getDataFromExcel = async (file: any, worksheetNumber: number = 1) => {
  const buffer = file.buffer;
  const workbook = new Workbook();
  await workbook.xlsx.load(buffer);
  const worksheet = workbook.getWorksheet(worksheetNumber);
  const headers = [];
  const dataArray = [];

  worksheet.eachRow((row, rowNumber) => {
    const rowData = {};
    row.eachCell((cell, colNumber) => {
      if (rowNumber === 1) {
        headers[colNumber] = cell.value; // 保存标题行
      } else {
        rowData[headers[colNumber]] = cell.value; // 将数据行转为对象
      }
    });

    if (rowNumber !== 1) {
      // 跳过标题行
      dataArray.push(rowData);
    }
  });
  return dataArray;
};

export async function convertArrayToExcel(data, sheetName = 'Sheet1') {
  // 创建一个新的工作簿
  const workbook = new Workbook();
  // 添加一个新的工作表
  const worksheet = workbook.addWorksheet(sheetName);

  // 检查数据是否为空
  if (data.length === 0) {
    console.log('数据为空，无法生成Excel表格');
    return;
  }

  // 获取对象数组的键作为表头
  const columns = Object.keys(data[0]).map((key) => ({
    header: key,
    key: key,
  }));

  // 设置工作表的列
  worksheet.columns = columns;

  // 添加数据到工作表
  data.forEach((item) => {
    worksheet.addRow(item);
  });

  return workbook;

}
